package cn.bone.springcloud.base.filter;

import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Order(0)
@Slf4j
@Component
public class MyLogGateWayFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("---- come in MyLogGateWayFilter");

        String username = exchange.getRequest().getQueryParams().getFirst("username");

        //如果参数中不包含username，直接返回，不走下面的过滤器
        if(username==null || "".equals(username)){
            log.info("用户名不存在，非法请求");
            ServerHttpResponse response = exchange.getResponse();
            JsonObject message = new JsonObject();
            message.addProperty("code","101");
            message.addProperty("message","没有用户名");
            byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type","text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(dataBuffer));
        }
        //验证通过，走后续的过滤器链
        return chain.filter(exchange);
    }
}
